<template>
  <div class="min-h-screen flex flex-col bg-gray-50">
    <!-- 顶部 -->
    <TopBar />
    <!-- 搜索 -->
    <div class="flex justify-between items-center w-4/5 mx-auto py-8">
      <!-- Logo -->
      <h1 class="w-6/24 text-center text-6xl"><a href="">Logo</a></h1>
      <!-- 搜索框 -->
      <div class="w-12/24 flex flex-col items-center">
        <div class="flex justify-center w-full">
          <input type="search" v-model="searchName"
            class="h-11 w-full border-2 border-red-400 rounded-l-lg px-3 focus:outline-none focus:ring-2 focus:ring-red-200"
            placeholder="正宗桂林米粉">
          <button
            class="h-11 w-1/7 bg-red-400 rounded-r-lg px-3 text-white text-lg font-bold cursor-pointer hover:bg-red-500 transition-colors"
            @click="clickSearch(searchName)">搜索</button>
        </div>
        <ul class="w-full flex search-items mt-1 overflow-x-auto py-1">
          <li class="whitespace-nowrap" @click="clickSearch('小米')">小米</li>
          <li class="whitespace-nowrap" @click="clickSearch('pro')">pro</li>
          <li class="whitespace-nowrap" @click="clickSearch('三只松鼠')">三只松鼠</li>
        </ul>
      </div>
      <div class="w-6/24 flex justify-end items-center">
      </div>
    </div>
    <!-- 中间 -->
    <div class="flex justify-between w-3/4 mx-auto">
      <!-- 分类 -->
      <div class="w-5/24 bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="px-5 py-3 font-bold text-lg border-b border-gray-100">分类</div>
        <ul class="category my-2 px-5 flex flex-wrap">
          <li class="flex py-2 px-0.5 hover:text-red-500 cursor-pointer transition-colors"
            v-for="(item, index) in category" :key="index">
            <div @click="clickSearch(item.categoryName)">{{ item.categoryName }}</div>
            <span class="mx-1 text-gray-400">/</span>
          </li>
        </ul>
      </div>
      <!-- 促销图 -->
      <div class='w-13/24 rounded-xl overflow-hidden shadow-sm'>
        <img src="https://picsum.photos/id/26/800/400" alt="促销轮播图" class="w-full h-full object-cover">
      </div>
      <!-- 个人中心 -->
      <div class="w-5/24 bg-white rounded-xl shadow-sm p-4 flex flex-col items-center">
        <div class="w-20 h-20 bg-red-300 rounded-full overflow-hidden mb-3">
          <img src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-full h-full object-cover">
        </div>
        <div class="text-center mb-4">
          <div class="text-xl">晚上好！<span class="font-bold text-red-500 cursor-pointer" @click="clickName">{{ userAccount
            || '请登录'
          }}</span></div>
          <div class=" text-gray-600">
            <span>收货地址</span>
            <span class="text-sm ml-3 text-gray-400 hover:text-black cursor-pointer"
              @click="addressShow = true">修改</span>
          </div>
        </div>
        <div class="px-3 mt-1 w-full">
          <ul class="info grid grid-cols-2 gap-3">
            <li @click="navigateTo('/cart')">
              <div class="text-red-500 font-bold">{{ cartCount }}</div>
              <div class="text-sm">购物车</div>
            </li>
            <li @click="navigateTo('/order')">
              <div class="text-red-500 font-bold">{{ orderCount }}</div>
              <div class="text-sm">全部订单</div>
            </li>
          </ul>
        </div>
        <el-button size="large" class="mt-5" @click="logout" type="primary" v-show="userId">退出登录</el-button>
      </div>
    </div>
    <!-- 底部 -->
    <div class="w-4/5 mx-auto my-5 border-t-3 border-t-amber-300 rounded-2xl p-3">
      <div class="text-red-400 flex gap-2.5 items-center text-2xl mb-3">
        <el-icon>
          <Promotion />
        </el-icon>
        <span>猜你喜欢</span>
      </div>
      <div class="flex flex-wrap justify-around gap-y-3 ">
        <Product v-for="(item, index) in products" :item="item" :key="index"
          @click="$router.push('/item/' + item.spuId)" />
      </div>
    </div>
    <!-- 侧边 -->
    <Aside />
    <Address v-show="addressShow" @hidden="addressShow = false" />
  </div>
</template>

<script setup>
import { getCart, getCartCountApi } from '@/apis/cart';
import { getCategoryAPI } from '@/apis/category';
import { getOrderCountApi } from '@/apis/order';
import { getAllProductApi } from '@/apis/products';
import { logoutApi } from '@/apis/user';
import Address from '@/components/Address.vue';
import Aside from '@/components/Aside.vue';
import Product from '@/components/Product.vue';
import TopBar from '@/components/TopBar.vue';
import { ElMessage } from 'element-plus';
import { onMounted, onUnmounted, ref, computed, reactive, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const userAccount = ref('')
const userId = ref('')
let category = ref([])
let orderCount = ref('')
let cartCount = ref('')
let addressShow = ref(false)
let products = ref([])
let searchName = ref('手机')
// 导航到指定路径
const navigateTo = (path) => {
  if (path !== route.path) {
    router.push(path);
  }
};

const clickName = () => {
  if (userId.value == null) {
    router.push('/passport/login')
  }
}

const getCate = async () => {
  try {
    let res = await getCategoryAPI()
    category.value = res.data
  } catch (error) {
    ElMessage.error('获取分类数据失败');
  }
}
const getOrderCount = async () => {
  try {
    let res = await getOrderCountApi()
    orderCount.value = res.data
  } catch (error) {
    ElMessage.error('获取订单数据失败');
  }
}
const getCartCount = async () => {
  try {
    let res = await getCartCountApi()
    cartCount.value = res.data
  } catch (error) {
    ElMessage.error('获取订单数据失败');
  }
}

const logout = async () => {
  try {
    await logoutApi()
    localStorage.removeItem('userAct')
    localStorage.removeItem('userId')
    userAccount.value = ''
    userId.value = ''
    router.push('/passport/login')
  } catch (error) {
    ElMessage.error('退出登录失败');
  }
}

const getProducts = async () => {
  let res = await getAllProductApi()
  products.value = res.data
}

const clickSearch = (name) => {
  router.push(`/items/${name}`)
}

onMounted(() => {
  userAccount.value = localStorage.getItem('userAct')
  userId.value = localStorage.getItem('userId')
  getCate()
  getOrderCount()
  getProducts()
  getCartCount()
  // getProvince()
})

// 监听路由参数变化，自动刷新数据
watch(() => route.params.name, () => {
  getProducts()
})
</script>

<style lang="scss" scoped>
.search-items {
  li {
    padding: 0 .5rem;
    color: #999;
    cursor: pointer;
    transition: color 0.3s;
  }

  li:hover {
    color: red;
  }
}

.category {
  li {
    li {
      padding: 0 .7rem;
      transition: all 0.3s;

      &:hover {
        color: red;
        text-decoration: underline;
      }
    }

    span {
      cursor: default;
    }

    &:hover {
      background-color: #fcfcfc;
      transition: background-color 0.3s;
    }
  }
}

.info {
  li {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    width: 100%;
    height: 4.5rem;
    background-color: var(--color-gray-50);
    border: 1px solid var(--color-gray-200);
    border-radius: 0.5rem;
    transition: all 0.3s;
    cursor: pointer;
  }

  li:hover {
    border-color: red;
  }
}
</style>